<template>
  <div>
    <el-dialog :title="title" :visible.sync="show" :before-close="cancel" width="1000px">
      <div style="display: flex; align-items: center">
        <el-date-picker
          @change="getList"
          :clearable="false"
          v-model="time"
          type="daterange"
          value-format="yyyy-MM-dd"
        />
        <slot></slot>
      </div>
      <div id="sellerSaleChart" style="width: 100%; height: 600px; margin-top: 15px"></div>
    </el-dialog>
  </div>
</template>

<script>
import { getSalesVolumePlatformPie } from '@/api/statistics/sellerSalePlatform'

import * as echarts from 'echarts'

const handlePercent = (value, total) => {
  let percent = (+(value / total) * 100).toFixed(2)
  isNaN(percent) ? (percent = 0) : percent
  return `${percent}%`
}
export default {
  name: 'sellerSaleChart',
  props: {
    /**
     * title
     */
    title: {
      type: String,
    },
    /**
     * legendWidth
     */
    legendWidth: {
      type: Number,
      default: 100,
    },
    formData: {
      type: Object,
      default: () => {},
    },
    /**
     * 控制显示隐藏
     */
    show: {
      type: Boolean,
      required: true,
      default: false,
    },
    /**
     * useThousand 使用千分符显示
     */
    useThousand: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      time: [],
    }
  },

  mounted() {},
  watch: {
    show: function (newValue) {
      if (newValue) {
        this.time = this.formData.time || []
        this.getList()
      }
    },
  },

  methods: {
    /** 初始化图表 */
    drawEcharts(data) {
      const _data = data?.map((item) => {
        return {
          value: item.value,
          name: item.name,
          labelLine: {
            show: true,
          },
          label: { show: true },
        }
      })
      var chartDom = document.getElementById('sellerSaleChart')
      this.myChart = echarts.init(chartDom)

      let tatalSale = 0
      data?.map((i) => {
        tatalSale += +i.value || 0
      })

      let self = this
      var option = {
        title: {
          text: [
            `{a|${this.title}:}`,
            '{b|}' /** */,
            `{c|${self.useThousand ? self.$thousand(tatalSale) : tatalSale}}`,
          ].join('\n'),
          textStyle: {
            rich: {
              a: {
                fontSize: 16,
                fontWeight: 'bold',
                lineHeight: 30,
              },
              b: {
                // lineHeight: 10, // 控制空行高度
              },
              c: {
                fontSize: 20,
                fontWeight: 'bold',
                lineHeight: 30,
              },
            },
          },
          textAlign: 'center',
          textVerticalAlign: 'middle',
          left: '59.5%',
          top: '50%',
        },
        tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(0,0,0,0.5)',
          padding: [10, 25],
          textStyle: {
            color: '#fff',
            fontSize: 13,
          },
          formatter: function (params) {
            const { name, value, color } = params
            return `
            <div style="font-weight:bold;">
              <span style="color:${color}"> ● </span>
              ${name} : ${value}
              </div>
            <div style="text-align:center;">${handlePercent(value, tatalSale)}</div>
              `
          },
        },
        legend: {
          orient: 'vertical',
          left: 10,
          itemWidth: 0,
          itemHeight: 0,
          formatter: function (name) {
            var data = option.series[0].data
            var target = data.filter(function (item) {
              return item.name === name
            })[0]
            var value = target ? target.value : ''
            return '{a|' + name + '}  ' + `${self.useThousand ? self.$thousand(value) : value}`
          },
          textStyle: {
            rich: {
              a: {
                width: self.legendWidth,
                height: 20,
                align: 'center',
                color: '#fff',
                backgroundColor: 'inherit',
              },
            },
          },
        },
        series: [
          {
            // name: '比例',
            type: 'pie',
            radius: ['35%', '80%'],
            center: ['60%', '50%'],
            itemStyle: {
              borderRadius: 5,
            },
            avoidLabelOverlap: true,
            selectedMode: 'single',
            data: _data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
            label: {
              normal: {
                formatter: function (e) {
                  let data = e.data
                  if (data.value == 0) {
                    data.labelLine.show = false
                    data.label.show = false
                  } else {
                    return `${data.name}:${self.useThousand ? self.$thousand(e.value) : (+e.value).toFixed()}`
                  }
                },
              },
            },
          },
        ],
      }

      option && this.myChart.setOption(option)
    },

    /**  */
    getList() {
      const data = {
        startTime: this.time[0],
        endTime: this.time[1],
        distrId: this.formData.distrId,
        type: this.formData.type,
        shopId: this.formData.shopId,
        address1: this.formData.address1,
        /**
         * 是否排除线下店铺 0-否 1-是
         */
        isExclude: this.formData.isExclude,
      }
      getSalesVolumePlatformPie(data).then((res) => {
        this.$nextTick(() => {
          this.drawEcharts(res.data)
        })
      })
    },

    cancel() {
      this.$emit('update:show', false)
    },
  },
}
</script>
